package com.iproinfo.index.controller;

import com.iproinfo.index.entity.User;
import com.iproinfo.index.mapper.MenuDao;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @Package: com.iproinfo.index.controller
 * @ClassName: MenuController
 * @Author: Zy_Rong
 * @CreateTime: 2020/12/30 14:53
 * @Description:生成图片验证码——注册登录类——密码使用PBKDF2加密
 */
@RestController
@RequestMapping("mymenu")
public class MenuController {

    @Resource
    private MenuDao menuDao;

    @Resource
    private PBKDF2Util pbkdf2Util;


    public static final String CAPTCHA_KEY = "session_captcha";
    /**
     * 生成验证码
     * @param request
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        // 生成图片
        int w = 135, h = 40;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

        // 将验证码存储在session以便登录时校验
        session.setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());

        //查询sesion中的验证码
        String sesionCode = (String) request.getSession().getAttribute(CAPTCHA_KEY);
        System.out.println("生成验证码："+sesionCode);
    }

    /**
     * 注册
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "addUser", produces = {"application/json;charset=UTF-8"})
    public String addTerms(@RequestBody User user)throws Exception{
        System.out.println("原始密码:"+user.getPassWord());
        String salt = pbkdf2Util.generateSalt();
        String pbkdf2 = pbkdf2Util.getEncryptedPassword(user.getPassWord(),salt);
        user.setPassWord(pbkdf2);
        user.setSalt(salt);
        System.out.println("盐值:"+salt);
        System.out.println("PBKDF2加盐后的密码:"+pbkdf2);
        int row=menuDao.addUser(user);
        if (row==1){
            return "注册成功";
        }
        return "注册失败";
    }

    /**
     * 登录
     * @param request
     * @return
     * @throws Exception
     */
   @RequestMapping(value="logins",method = RequestMethod.POST)
    public String loginCheck(HttpServletRequest request,@RequestBody User u) throws Exception {
       User user=new User();
       //查询时间下面判断用户登录失败次数会用到
       SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       Date date = new Date(System.currentTimeMillis());
       String newtime=formatter.format(date);
       System.out.println(newtime);//当前时间
       Date now = new Date();
       Date now_10 = new Date(now.getTime() - 600000);
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String oldTime = dateFormat.format(now_10);
       System.out.println(oldTime);//10分钟前的时间
        //获取sesion中的验证码
        String sesionCode = (String) request.getSession().getAttribute(CAPTCHA_KEY);
        if (u.getCa().equals("")|u.getCa()==null){
            return "请输入验证码。";
        }
        if(sesionCode!=null) {
            if (!u.getCa().equalsIgnoreCase(sesionCode.toLowerCase())) {
                return "验证码不匹配。";
            }
        }else {
            //未获取到sesion中的验证码
            return "验证码加载失败";
        }
        int number=menuDao.logonFailureTimes(u.getUserName(),newtime,oldTime);
        if (number>=3){
        return "错误次数已达限制,账号已锁定请10分钟再试。";
        }
        //通过用户输入的userName查找盐值
          user=menuDao.findSalt(u.getUserName());
        if(Objects.isNull(user)){
            //插入一条失败记录
            menuDao.failedUserLogin(u.getUserName(),newtime);
            //不提示账号不存在更加安全
            return "账号密码不匹配,3次将锁定账号10分钟。";
        }else {
            System.out.println("用户输入密码:"+u.getPassWord());
            //用户输入的密码加上当时注册的盐值 重新得出加盐后的密码
            String pbkdf2 = pbkdf2Util.getEncryptedPassword(u.getPassWord(),user.getSalt());
            System.out.println("盐值:"+user.getSalt());
            System.out.println("PBKDF2加盐后的密码:"+pbkdf2);
            //拿到账号和加盐后的密码进行查询
               user=menuDao.findOneUser(u.getUserName(), pbkdf2);
            if(Objects.isNull(user)){
                //插入一条失败记录
                menuDao.failedUserLogin(u.getUserName(),newtime);
                return "账号密码不匹配,3次将锁定账号10分钟。";
            }
        }
        return "1";
    }
}
